/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sjtu.servlet;

import com.sjtu.bean.BookBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author p w
 */
public class BookByCategoryServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doWork(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doWork(request, response);
    }

    public void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("*************************");
        String obj = request.getParameter("obj");
        JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PrintWriter writer = response.getWriter();
        try {
            String bookname = jsonObj.getString("categoryName");
            ArrayList<BookBean> books = BookBean.getBookByCategory(bookname);
            ArrayList<String> urlList = new ArrayList<String>();
            ArrayList<String> bookNameList = new ArrayList<String>();
            ArrayList<String> authorList = new ArrayList<String>();
            ArrayList<String> publisherList = new ArrayList<String>();
            ArrayList<Integer>idList = new ArrayList<Integer>();
            for(int i=0;i<books.size();i++){
                urlList.add(books.get(i).getCoverURL());
                bookNameList.add(books.get(i).getName());
                authorList.add(books.get(i).getAuthor());
                publisherList.add(books.get(i).getPublisher());
                idList.add(books.get(i).getId());
            }
            JSONObject jsonRes = new JSONObject();
            jsonRes.put("bookNameList", bookNameList);
            jsonRes.put("authorList", authorList);
            jsonRes.put("publisherList", publisherList);
            jsonRes.put("idList", idList);
            jsonRes.put("urlList", urlList);
            writer.write(jsonRes.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        writer.flush();
        writer.close();
    }
}
